package com.devops.filter;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.devops.admin.po.DOSBaseUserPo;
import com.devops.common.utils.Message;
import com.devops.constant.DevOpsConstant;
import com.devops.shiro.service.DOSBaseUserService;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author jxt
 * @Notes
 * @date 2024/1/4 10:20
 */
@Slf4j
@WebFilter(value = {"/api/k8s/*","/api/ip/*"})
public class UserApiFilter implements Filter {
    @Resource
    private DOSBaseUserService baseUserService;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        String apiToken = ((HttpServletRequest)servletRequest).getHeader("apiToken");
        boolean auth = false;
        if (StrUtil.isNotBlank(apiToken)) {
            List<DOSBaseUserPo> userPoList = baseUserService.getUserByApiToken(apiToken);
            if (CollUtil.isNotEmpty(userPoList)) {
                DOSBaseUserPo userPo = userPoList.get(0);
                servletRequest.setAttribute(DevOpsConstant.API_USER_ID, userPo.getId());
                auth = true;
            }
        }
        if (auth) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            Message message = new Message(String.valueOf(HttpServletResponse.SC_UNAUTHORIZED), "unauthorized", null);
            httpResponse.getWriter().write(JSONUtil.toJsonStr(message));
        }
    }
}
